package com.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.dto.LoginRequest;
import com.book.entity.User;
import com.book.mapper.UserMapper;
import com.book.service.UserService;
import com.book.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Override
    public String login(LoginRequest loginRequest) {
        // 验证验证码
        String captchaKey = "captcha:" + loginRequest.getCaptchaKey();
        String captchaCode = redisTemplate.opsForValue().get(captchaKey);
        
        if (captchaCode == null) {
            throw new RuntimeException("验证码已过期");
        }
        
        if (!captchaCode.equalsIgnoreCase(loginRequest.getCaptcha())) {
            throw new RuntimeException("验证码错误");
        }
        
        // 删除验证码
        redisTemplate.delete(captchaKey);
        
        // 查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginRequest.getUsername());
        User user = this.getOne(queryWrapper);
        
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证密码（这里使用MD5加密，实际项目中建议使用BCrypt）
        String encryptedPassword = DigestUtils.md5DigestAsHex(loginRequest.getPassword().getBytes());
        if (!user.getPassword().equals(encryptedPassword)) {
            throw new RuntimeException("密码错误");
        }
        
        if (user.getStatus() == 0) {
            throw new RuntimeException("用户已被禁用");
        }
        
        // 生成JWT token
        return jwtUtil.generateToken(user.getUsername());
    }
    
    @Override
    public User getUserByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return this.getOne(queryWrapper);
    }
} 